package com.everwin.framework.shiro.web.filter;

import com.everwin.common.utils.ServletUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Date: 2019/6/25 11:06
 * @DESC: 重写UserFilter拦截器
 */
public class MyUserFilter extends AccessControlFilter {
    /**
     * 退出后重定向的地址
     */
    private String loginUrl;

    public String getLoginUrl()
    {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl)
    {
        this.loginUrl = loginUrl;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        if (isLoginRequest(request, response)) {
            return true;
        } else {
            Subject subject = getSubject(request, response);
            return subject.getPrincipal() != null;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        if(ServletUtils.isAjaxRequest(httpServletRequest)){
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setStatus(600);
            httpServletResponse.getWriter().write("{\"code\":\"600\",\"msg\":\"需要登陆继续访问！\"}");
        }else {
            setLoginUrl(getLoginUrl());
            saveRequestAndRedirectToLogin(request, response);
        }
        return false;
    }

}
